#include "TcpServer.hpp"
#include "Calculator.hpp"
#include "log.hpp"
#include <memory>

Calculator calculator;

void DefaultOnMessage(std::weak_ptr<Connection> conn);
// 因为TCP粘包,此实现方式有bug

int main()
{
    std::shared_ptr<TcpServer> svr(new TcpServer(8888, DefaultOnMessage));
    svr->Init();
    svr->Loop();
    return 0;
}

void DefaultOnMessage(std::weak_ptr<Connection> conn)
{
    if (std::shared_ptr<Connection> connection = conn.lock()) {
        // 对报文进行处理
        std::cout << "上层得到了数据: " << connection->InBuffer() << std::endl;
        std::string response_str = calculator.Handler(connection->InBuffer());
        if (response_str.empty()) { return; }
        LOG(Info, "response_str: %s", response_str.c_str());
        // 将response_str发出去
        connection->AppendOutBuffer(response_str);

        if (std::shared_ptr<TcpServer> tcpserver_ptr = connection->_tcp_server_ptr.lock()) {
            // 因此TcpServer要用shared_ptr
            tcpserver_ptr->Sender(connection);
        }
        else {
            LOG(Warning, "connection->_tcp_server_ptr is null!");
            return;
        }     
    }
    else{
        LOG(Warning, "weak_ptr conn is null");
        return;
    }
}